<?php
/**
 * 账户处理类
 */
namespace app\v2\model;

use think\Db;
use think\cache\driver\Redis;
use think\Model;
class User extends Model 
{   
    
    /**
     *  默认时间戳是字段  creat_time
     *  默认时间戳是格式  datetime
     */
    protected $name = 'user';
    protected $createTime = 'reg_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = 'datetime';
    protected $insert = [
        'status' => 1,
    ];  



    public function register($param,$acode = "",$bcode = "")
    {
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $password = $this->Password();
        $param['password'] = user_md5($password,$auth_key = 'qhdkb');
        $param['phone'] = $param['username'];
        $param['reg_ip'] = getClientIP();

        $check = $this->ExistAccount($param['phone']);
        if(!$check){
            $this->error = '手机号已被注册';
            return false;
        }
        $this->startTrans();
        try {
            $res1=$this->data($param)
                 ->allowField(true)
                 ->isUpdate(false)
                 ->save();

            #添加 用户 信息
            $userinfo = new UserInfo();
            $paramInfo['phone']       = $param['phone'];
            $paramInfo['uid']         = $this->uid;
            $paramInfo['rand_code']   = md5($paramInfo['uid'].microtime());
            $paramInfo['mobile_type'] = $param['mobile_type'];
            $paramInfo['os']          = $param['os'];
            // 3/13
            $paramInfo['name']        = $param['name'];

            $paramInfo['business_id'] = $param['business'];
            $paramInfo['insurance']   = $param['insurance']; //是否勾选投保




            $res2=$userinfo->data($paramInfo)
                     ->allowField(true)
                     ->isUpdate(false)
                     ->save();
            #添加 邀请关系
            $InviteModel = new Invite();
            $res3=$InviteModel->creatcode($this->uid,11,$acode,$bcode);
            if(false === $res3)
            {
                $this->error = '注册失败';
                return false;
            }
             
            #添加 奖励表
            $InviteCommissionModel =  new InviteCommission();
            $res4=$InviteCommissionModel->addCom($this->uid);

            #初始化积分信息
            $score = new Score();
            $res5=$score->data(array('uid'=>$this->uid,'score'=>0,"score_total"=>0))
                  ->allowField(true)
                  ->isUpdate(false)
                  ->save();
                  
            $this->commit() ;
            return $this->uid ;
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '添加失败';
            return false;
        }
    }


    /**
     * 推广注册第一步操作
     * @param $param
     * @param string $acode
     * @param string $bcode
     * @return bool|mixed
     * @throws \think\exception\PDOException
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/6/7
     */
    public function newRegister($param,$acode = "",$bcode = "")
    {

        if(!$param['phone']){
            $this->error = '手机号必须填写';
            return false;
        }

        $password = $this->password();
        $param['password'] = user_md5($password,$auth_key = 'qhdkb');
        $param['username'] = $param['phone'];
        $param['reg_ip'] = getClientIP();
        $param['reg_time'] = date('Y-m-d H:i:s',time());;
        
        $check = $this->ExistAccount($param['phone']);
        if(!$check){
            $this->error = '手机号已被注册';
            return false;
        }
        $this->startTrans();
        try {

            $data_business['password'] = $param['password'];
            $data_business['username'] = $param['username'];
            $data_business['reg_ip']   = $param['reg_ip'];
            $data_business['reg_time'] = $param['reg_time'];
            $data_business['phone']    = $param['phone'];
            $connect_user              = Db::connect('db_business');
            $connect_user->table('qh_user')->insert($data_business);
            

            # 添加用户信息
            $uid = $connect_user->table('qh_user')->where(['username'=>$param['phone']])->value('uid');
            $paramInfo['phone']       = $param['phone'];
            $paramInfo['uid']         = $uid;
            $paramInfo['rand_code']   = md5($paramInfo['uid'].microtime());
            $paramInfo['mobile_type'] = $param['mobile_type'];
            $paramInfo['os']          = $param['os'];
            $paramInfo['name']        = $param['name'];
            $paramInfo['business_id'] = $param['business'];
            $paramInfo['insurance']   = $param['insurance']; //是否勾选投保
            $paramInfo['create_time'] = $param['reg_time']; //是否勾选投保

            $connect_user->table('qh_user_info')->insert($paramInfo);
      

            #添加 邀请关系
            $data['uid']           = $uid;
            $data['bcode']         = $bcode;
            $count                 = $connect_user->table('qh_binvite_commission')->where(['bcode'=>$bcode])->count();
            $data['yaoqingtongji'] = $count+1;
            $data['creat_time']    = date('Y-m-d H:i:s',time());
            $connect_user->table('qh_binvite_commission')->insert($data);

            
            # 本库的邀请关系
            $data_tui['uid']           = $uid;
            $data_tui['bcode']         = $bcode;
            $data_tui['yaoqingtongji'] = $count+1;
            $data_tui['creat_time']    = date('Y-m-d H:i:s',time());
            $data_tui['pj_type']       = config('pj_type');
            Db::name('binvite_commission')->insert($data_tui);
            
            $this->pageStatistics('firstPart');                     //统计计数
            $this->commit() ;
            return $uid;
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '添加失败';
            return false;
        }

    }


    /**
     * 生成随机密码
     * @param int $pw_length
     * @return string
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/6/7
     */
    public function password($pw_length = 6)
    {
        $randpwd = '';
        for ($i = 0; $i < $pw_length; $i++)
        {
            $randpwd .= chr(mt_rand(33, 126));
        }
        return $randpwd;
    }

    /**
     * 推广注册第二步操作
     * @param $param
     * @return bool
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/6/7
     */
    public function finishUser($param)
    {
        $uid = $param['uid'];
        if(!$param['pwd']){
            $this->error= '密码不存在';
            return false;
        }
 
        $where_finsh['pj_type'] = config('pj_type');
        $where_finsh['uid'] = $uid;
        $res =  Db::name('binvite_commission')->where($where_finsh)->value('is_pwd');
        if($res==1){
            $this->error= '您已经填写完成，无需重复点击';
            return false;
        } 
        
        $password = user_md5($param['pwd'],$auth_key = 'qhdkb');
        if(!$uid){
            $this->error='uid不存在';
            return false;
        }
        $data['password'] = $password;
        $this->startTrans();
        try{
            Db::connect('db_business')->table('qh_user')->where(['uid'=>$uid])->update($data);
            $datas['zmf'] = $param['zmf'];
            $datas['age'] = $param['age'];
            Db::connect('db_business')->table('qh_user_info')->where(['uid'=>$uid])->update($datas);
            Db::name('binvite_commission')->where(['uid'=>$uid])->update(['is_pwd'=>1]);
            $this->pageStatistics('secondPart');
            $this->commit();
            return $uid;
        }catch (\Exception $e){
            $this->error='失败';
            return false;
        }

    }

    /**
     * 统计第一步和第二步用户数量转化
     * @param string $type
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/6/7
     */
    public function pageStatistics($type='')
    {
        $redis = new Redis();
        $redis->select('2');
        $dateName = date('Y-m-d');
        $part = $redis->get($dateName.':'.$type);
        if(!$part){
            $redis->set($dateName.':'.$type,0,86400*3);
        }
        $redis->inc($dateName.':'.$type);
    }

    /**
     * 邀请关系加入队列
     * @param $param
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/6/7
     */
    public function redisPush($param)
    {
        $redis = new Redis();
        $redis->rpush('work',$param);
    }


    public function ExistAccount($phone)
    {
        $res =  Db::connect('db_business')->table('qh_user')->where('username', $phone)->find();
        if($res){
            return false;
        }
        return true;
    }
    /**
     * 登陆
     * @zwr
     * @DateTime 2017-06-28T19:19:56+0800
     * @param    [type]                   $username [用户名]
     * @param    [type]                   $password [密码]
     * @return   [type]                       
     */
    public function login($username,$password)
    {
        if (!$username) {
            $this->error = '帐号不能为空';
            return false;
        }
        if (!$password){
            $this->error = '密码不能为空';
            return false;
        }

        $map['username'] = $username;
        $userInfo = $this->where($map)->find();
        if (!$userInfo) {
            $this->error = '帐号不存在';
            return false;
        }
        $userInfo = $userInfo->toArray();
        if (user_md5($password,$auth_key = 'qhdkb') !== $userInfo['password']) {
            $this->error = '密码错误';
            return false;
        }

        if ($userInfo['status'] === 0) {
            $this->error = '帐号已被禁用';
            return false;
        }
        unset($userInfo['password']);
        unset($userInfo['reg_ip']);
        unset($userInfo['last_login_ip']);
        unset($userInfo['last_login_time']);
        unset($userInfo['reg_time']);
        $this->updateLoginInfo($userInfo['uid'],$userInfo['login_count']);
        #发放注册并首次登录奖励
        $InviteCommissionModel =  new InviteCommission();

        #登录次数 如果为0 说明是第一次 登录
        // if(!$userInfo['login_count']){
        //  $InviteCommissionModel ->SignLoginReward($uid);
            
        // }
        return $userInfo;
    }
    public function updateLoginInfo($uid,$login_count)
    {
        $data['last_login_time'] = date("Y-m-d H:i:s",time());
        $data['last_login_ip']   = getClientIP();
        $data['login_count']    = $login_count+1;
        $res = $this->allowField(true)->save($data, ['uid' => $uid]);
    }
    /**
     * 获得用户信息
     * @zwr
     * @DateTime 2017-7-6 10:49:13
     * @param    [type]     $uid [description]
     * @return   [type]          [description]
     */
    public function getInfoByUid($uid)
    {
        $info = $this->where(array('uid'=>$uid))->find();
        return $info?$info->toArray():array();
    }

    /**
     * [changPassword description]
     * @zwr
     * @DateTime 2017-06-28T19:49:16+0800
     * @param    string                   $usernmame 用户名
     * @param    string                   $password  新密码
     * @return   bool                              
     */
    public function changPassword($username,$password)
    {
        if(!$username){
            $this->error = '用户名不能为空';
            return false;           
        }
        if(!$password || $password==''){
            $this->error = '新密码不能为空';
            return false;           
        }
        $userInfo = $this->where('username', $username)->find(); 
        if ($userInfo['status'] === 0) {
            $this->error = '帐号已被禁用';
            return false;
        }       
   //   if (user_md5($password,$auth_key = 'qhdkb') == $userInfo['password']) {
            // $this->error = '密码没有改变';
            // return false;
   //   }
        $password = user_md5($password,$auth_key = 'qhdkb');
        $res = $this->where('uid', $userInfo['uid'])->setField('password',$password);
        if(false!==$res){
            $cleanToken = DB::name('user_token')->where('uid', $userInfo['uid'])->update(['token'=>'']);
            return true;
        }
        $this->error = '修改失败';
        return false;           
    }

    /**
     * 修改支付密码
     * @author yhq <934797303@qq.com>
     * @date   2018-04-10
     * @param    string     $usernmame     用户名
     * @param    string     $pay_password  支付密码
     * @return   bool                      
     */
    public function changePayPassword($username,$pay_password)
    {
        if(!$username){
            $this->error = '手机号不能为空';
            return false;           
        }
        if(!$pay_password || $pay_password==''){
            $this->error = '新密码不能为空';
            return false;           
        }
        //判断是否为数字
        $pay_password = is_numeric($pay_password) ? $pay_password : '';
        if (strlen($pay_password) != 6) {
            $this->error = '支付密码为6位数字';
            return false; 
        }

        $userInfo = $this->where('username', $username)->find(); 
        if ($userInfo['status'] === 0) {
            $this->error = '帐号已被禁用';
            return false;
        }       
   //   if (user_md5($pay_password,$auth_key = 'qhdkb') == $userInfo['pay_password']) {
            // $this->error = '密码没有改变';
            // return false;
   //   }
        $pay_password = user_md5($pay_password,$auth_key = 'qhdkb');
        $res = $this->where('uid', $userInfo['uid'])->setField('pay_password',$pay_password);
        if(false!==$res){
            return true;
        }
        $this->error = '修改失败';
        return false;           
    }


    /**
     * 校验支付密码
     * @author yhq <934797303@qq.com>
     * @date   2018-04-10
     * @param  [string]     $uid          [uid]
     * @param  [string]     $pay_password [支付密码]
     * @return [boolean]     
     */
    public function checkPayPassword($uid, $pay_password)
    {
        $userInfo = $this->where('uid',$uid)->field('pay_password')->find();
        if (!$userInfo) {
            $this->error = '帐号不存在';
            return false;
        }

        if(empty($userInfo['pay_password'])){
            // 请先设置支付密码
            $this->error = '406';
            return false;
        }

        $redis = new Redis;
        $redis -> select(config('redis_select'));       
        $redisKey = config('project_name').':checkPayPassword:'.$uid;
        $errorNum = $redis->get($redisKey);    //读取缓存
        $errorNum = $errorNum ? $errorNum : 3; // 错误次数
        $expire   = 3600;  // 缓存时间 秒

        if($errorNum <= 1){
            $this->error = '支付密码输错次数过多，请一个小时后重试';
            return false;  
        }

        $userInfo = $userInfo->toArray();
        if (user_md5($pay_password,$auth_key = 'qhdkb') !== $userInfo['pay_password']) {
            $errorNum-=1;
            $redis->set($redisKey, $errorNum, $expire); //写入缓存

            $this->error = $errorNum==1 ? '如再次输错请一个小时后再试' : '支付密码错误，还剩'.$errorNum.'次机会'; 
            return false;  
        }

        return true;
    }


  
     /**
     * 记录用户下载
     * @param $uid  用户id
     * @return bool
     * @throws \think\exception\PDOException
     * @AUTHER 范俊成
     * @DATE 2018/4/16
     */
    public function download($flag='',$type='',$uid='')
    {

        $type = strtolower($type);
        if(empty($type) && empty($uid)){
            $data['download_time'] = date('Y-m-d H:i:s',time());
            $data['type'] =$flag;
            Db::name('extend')->insert($data);
            return array('data'=>'下载成功');
        }else{
            $res = Db::name('extend_user')->where(array('uid'=>$uid))->find();
            if($res){
                return array('data'=>'已经激活过了');
            }
            $data['uid'] = $uid;
            $data['type']=$type;   
            $data['active_time'] = date('Y-m-d H:i:s',time());
            Db::name('extend_user')->insert($data);
            return array('data'=>'激活成功');
        }

    }



}
